﻿using System;

namespace PoolKit
{
    internal class RepairStrategyThreadSafe<TResource> : RepairStrategy<TResource>
    {
        private readonly RepairStrategy<TResource> _nonThreadSafeStrategy;
        private readonly object _operationExecutionCriticalSection = new object();

        public RepairStrategyThreadSafe(RepairStrategy<TResource> nonThreadSafeStrategy)
        {
            if (nonThreadSafeStrategy == null) throw new ArgumentNullException("nonThreadSafeStrategy");

            if (nonThreadSafeStrategy.ThreadingContract == ThreadingContract.Multithreaded)
            {
                throw new ArgumentException(Resources.AlreadyAThreadSafeStrategy);
            }

            _nonThreadSafeStrategy = nonThreadSafeStrategy;
        }

        public override string ToString()
        {
            return _nonThreadSafeStrategy.ToString();
        }

        public override TResource Repair(TResource resourceToRepair)
        {
            lock (_operationExecutionCriticalSection)
            {
                return _nonThreadSafeStrategy.Repair(resourceToRepair);
            }
        }

        public override ThreadingContract ThreadingContract
        {
            get
            {
                return PoolKit.ThreadingContract.Multithreaded;
            }
        }
    }
}